<template>
  <div class="permission-node" :style="{ marginLeft: isRoot ? '0px' : depth * 20 + 'px' }">
    <div v-if="hasChildren">
      <div :class="['node-header', { 'root-title': isRoot, 'clickable': true }]">
        <el-checkbox
            :model-value="isChecked(item)"
            @change="handleCheck(item, $event)"
        />
        <span @click="toggleExpand" style="cursor: pointer;">{{ isExpanded ? '▼' : '▶' }}</span>
        <strong>{{ item.pname }}</strong>
      </div>

      <div v-show="isExpanded">
        <!-- 第一部分：叶子节点（无子节点）—— 横向显示 -->
        <div v-if="leafChildren.length > 0" class="buttons-container">
          <div v-for="child in leafChildren" :key="child.id" class="permission-item">
            <el-checkbox
                :model-value="isChecked(child)"
                @change="handleCheck(child, $event)"
            />
            <el-button type="text">{{ child.pname }}</el-button>
          </div>
        </div>

        <!-- 第二部分：非叶子节点（有子节点）—— 竖向显示 -->
        <div v-if="nonLeafChildren.length > 0" class="subtree-container">
          <RolePermissionItem
              v-for="child in nonLeafChildren"
              :key="child.id"
              :item="child"
              :depth="depth + 1"
              :checked-permissions="checkedPermissions"
              @update:checkedPermissions="val => emit('update:checkedPermissions', val)"
          />
        </div>
      </div>
    </div>

    <div v-else class="buttons-container permission-item">
      <el-checkbox
          :model-value="isChecked(item)"
          @change="handleCheck(item, $event)"
      />
      <el-button type="text">{{ item.pname }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  item: Object,
  depth: { type: Number, default: 0 },
  checkedPermissions: { type: Array, default: () => [] }
})
const emit = defineEmits(['update:checkedPermissions'])

const isExpanded = ref(true)
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

const hasChildren = computed(() => props.item.children && props.item.children.length > 0)
const childrenAllLeaf = computed(() =>
    hasChildren.value &&
    props.item.children.every(child => !child.children || child.children.length === 0)
)
const isRoot = computed(() => props.item.parentId === 0)

const isChecked = (node) => props.checkedPermissions.includes(node.id)

// 递归收集所有子节点 ID
const collectAllIds = (nodes) => {
  let ids = []
  for (const node of nodes || []) {
    ids.push(node.id)
    if (node.children && node.children.length > 0) {
      ids = ids.concat(collectAllIds(node.children))
    }
  }
  return ids
}

const handleCheck = (node, checked) => {
  let newChecked = [...props.checkedPermissions]

  if (checked) {
    if (!newChecked.includes(node.id)) newChecked.push(node.id)

    // 向上勾选所有父节点
    let parent = node.parent
    while (parent) {
      if (!newChecked.includes(parent.id)) newChecked.push(parent.id)
      parent = parent.parent
    }
  } else {
    // 取消当前节点和所有子节点
    const idsToRemove = [node.id, ...collectAllIds(node.children)]
    newChecked = newChecked.filter(id => !idsToRemove.includes(id))
  }

  emit('update:checkedPermissions', [...new Set(newChecked)])
}

const leafChildren = computed(() =>
    props.item.children?.filter(child => !child.children || child.children.length === 0) || []
)

const nonLeafChildren = computed(() =>
    props.item.children?.filter(child => child.children && child.children.length > 0) || []
)
</script>

<style scoped>
.permission-node {
  margin-top: 8px;
}
.node-header {
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 6px;
  user-select: none;
  width: 100%;
}
.root-title {
  background-color: #d9eaff;
  color: #409eff;
  padding: 8px 12px;
  border-radius: 6px;
  margin-bottom: 10px;
  font-size: 16px;
}
.buttons-container {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 8px;
}
.permission-item {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}
.subtree-container {
  background-color: #f9f9f9;
  padding: 10px;
  border-left: 3px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 10px;
}
</style>
